<template>
    <div>
        <el-form
                ref="dataForm"
                status-icon
                label-width="0px"
        >
            <el-descriptions :column="1" border>
                <el-descriptions-item labelStyle="width: 10%" contentStyle="width: 90%">
                    <template slot="label"> 上传文件</template>
                    <div>
                        <el-upload
                        class="upload-demo"
                                drag
                                :action="uploadUrl"
                                multiple
                                :on-success="uploadSuccess"
                                :on-progress="uploadProgress" 
                                :before-upload = "beforeUpload"                            
                                :headers="uploadHeader"
                                :on-error="uploadError"
                                :show-file-list="false"
                        >
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">请先下载<a target="_blank" :href="templateUrl">导入模版</a>，只能上传excel文件，且不超过2M。
                            </div>
                        </el-upload>
                        <div style="background-color:beige;padding: 10px;margin-top:10px;" v-show="progressVisible">
                            <div>数据处理中，请勿刷新或退回页面，处理完成后请点击取消按钮退出</div>
                            <el-row style="padding: 10px;">
                                <el-col :span="5"><div class="grid-content bg-purple">正在处理：{{ progressText }}</div></el-col>
                                <el-col :span="3"><div class="grid-content bg-purple-light">总数：{{ total }}</div></el-col>
                                <el-col :span="3"><div class="grid-content bg-purple">已处理：{{ curr }}</div></el-col>
                                <el-col :span="4"><div class="grid-content bg-purple-light">处理速度：{{speed}} 条/分钟</div></el-col>
                                <el-col :span="4"><div class="grid-content bg-purple-light">即时速度：{{real}} 条/分钟</div></el-col>
                                <el-col :span="5"><div class="grid-content bg-purple-light">已用时：{{ days }} 天 {{hours}} 小时 {{minutes}} 分钟 {{ seconds }} 秒</div></el-col>
                            </el-row>
                            <el-progress  :text-inside="true" :stroke-width="26" :percentage=progressNum :status=progressStatus />
                        </div>
                        <div v-show="errShow" style="margin-left: 20px;margin-top: 20px;">
                            <div>
                                <div>
                                    <font style="color: red;">文件处理发现错误，请下载处理文件，按照错误提示修改后再次上传</font>
                                </div>
                                <a :href="errFileUrl"><img src="../../../assets/img/excel.jpg" width="30" /></a>
                            </div>
                        </div>
                    </div>
                </el-descriptions-item>

                <el-descriptions-item labelStyle="width: 10%" contentStyle="width: 90%">
                    <el-form-item label=" ">
                        <el-button @click="handleDialogVisible(true)" size="small">取 消</el-button>
                    </el-form-item>
                </el-descriptions-item>
            </el-descriptions>
        </el-form>

    </div>
</template>

<script>
    import {getToken} from "@/common/token";
    import {getProgress, getQueueStatus, gucyTest} from '@/api/data/data'
    import moment from "moment";
    import 'moment/locale/zh-cn'
    export default {
        props: ["rowData", "dialogStatus"],
        components: {},
        data() {
            return {
                uploadUrl: process.env.VUE_APP_API + "/data/data/uploadImportData",
                uploadHeader: {
                    Authorization: "Bearer " + getToken(),
                },
                templateUrl: process.env.VUE_APP_API + "/tpl/肺癌导入模版.xlsx",
                createLoading: false,
                updateLoading: false,
                timeoutSetting: 5000,
                progressNum: 0,
                progressStatus: "warning",
                progressText: " ",
                progressVisible: false,
                result: null,
                tiemStart: Date.now(),
                total: 0,
                curr: 0,
                speed: 0,
                days: 0,
                hours: 0,
                minutes: 0,
                seconds: 0,
                real: 0,
                lastCurr: 0,
                errShow: false,
                errFileUrl: "",
                btnDisable: false
            };
        },
        created() {

        },
        methods: {
            uploadProgress(e1) {
                //console.log(e1)
                //console.log(e2)
                this.progressNum = e1.percent
                //console.log(e3)
                // this.loading = this.$loading({
                //     lock: true,
                //     text: '数据导入中，请耐心等待！',
                //     spinner: 'el-icon-loading',
                //     background: 'rgba(0, 0, 0, 0.7)'
                // });
                //this.progressVisible = true;
                //this.progressMonitor();
                
            },
            beforeUpload(file) {
                return new Promise((resolve, reject) => {
                    getQueueStatus({}).then(res=>{
                        //console.log(res)
                        if(res.code==200) {
                            this.progressVisible = true
                            resolve(file);
                        }
                        else {
                            reject(new Error('服务器繁忙，请稍后再试'));
                        }
                    }).catch(e =>{
                        reject(new Error('上传异常失败，请稍后再试'));
                    })
                })
            },
            progressMonitor() {
                this.errShow = false
                getProgress(this.result).then(res => {
                    //console.log(res)
                    //console.log(this)
                    if(res.code == 200) {
                        //console.log(typeof(res.data))
                        try{
                            //var obj = JSON.parse(res.data)
                            if(res.data.status) {
                                if(res.data.status=="done"){

                                    this.msgSuccess(res.msg)
                                    //console.log(res.data)
                                    if(res.data.error) {
                                        this.errShow = res.data.error
                                        this.errFileUrl = process.env.VUE_APP_API + res.data.fileInfo
                                    }
                                    this.progressNum = 100
                                    this.progressText = "完成"
                                    this.btnDisable = false                                    
                                }
                                else{
                                    this.msgError(res.msg)
                                }
                            }
                            else {
                                //console.log(res.data.total)
                                if(res.data.total && res.data.total > 0) {
                                    this.progressText = res.data.sfz
                                    this.total = res.data.total
                                    this.curr = res.data.curr

                                    let ts = moment.duration(Date.now()-this.tiemStart)
                                    this.days = ts.days()
                                    this.hours = ts.hours()
                                    this.minutes = ts.minutes()
                                    this.seconds = ts.seconds()
                                    
                                    this.speed = parseInt( res.data.curr * 60 / ts.asSeconds())
                                    this.real = (res.data.curr - this.lastCurr) * 60000 / this.timeoutSetting
                                    this.lastCurr = res.data.curr
                                    let percent = parseInt(res.data.curr * 100/res.data.total)
                                    this.progressNum = percent
                                }
                                setTimeout(() => {
                                    this.progressMonitor()
                                }, this.timeoutSetting);   
                            }
                        }
                        catch(e) {
                            console.log(e)
                        }
                    }
                    // setTimeout(() => {
                    //     this.progressMonitor()
                    // }, this.timeoutSetting);                  
                    // if (res.code === 200) {
                    //     this.progressNum = res.data.counter

                    // } else {
                    //     this.msgError(res.msg);
                    // }
                }).catch(e => {
                    //console.log('errhere')
                    console.log(e)
                })
            },
            uploadSuccess: function (res) {
                //console.log('success')
                //console.log(res)
                if(res.code==200) {
                    this.result = res.data
                    this.progressText = "..."
                    this.progressNum = 0
                    this.progressStatus = "success"
                    this.lastCurr = 0
                    this.tiemStart = new Date()
                    this.btnDisable = true
                    this.progressMonitor()
                }
                else {
                    this.msgError(res.msg)
                }
                //this.progressMonitor()
                // console.log(res)
                // if (res.code === 200) {
                //     this.msgSuccess(res.msg);
                // } else {
                //     this.msgError(res.msg);
                // }
                //this.loading.close();
                //this.handleDialogVisible(true);
            },
            uploadError: function () {
                this.msgError("后端错误，请联系管理员");
                this.handleDialogVisible(false);

            },
            //父页面的回调事件
            handleDialogVisible(isUpdate) {
                this.dialogVisible = false;
                this.$emit("childByDialogVisible", this.dialogVisible, isUpdate);
            },
        },
        watch: {},
    };
</script>

<style lang="scss" scoped="scoped">
    .el-upload__tip {
        font-size: 15px;

        a {
            color: blue;
        }
    }
</style>
